/***************************************************************
 * This script demonstrates how to import documents from a local
 * folder structure.
 ****************************************************************/
import org.doofer.*

/**
 * Imports files & folders from the samples/data folder
 * @author Mark Davidson
 */
class Importer {

    def params = [:]

    // Constructor
    Importer(Map args) {
        params = args
    }

    // Execute the import
    def execute() {
        params.source = 'data'         // specify base source dir
        def objectType = 'dm_document'

        if(params.target) {
            // Open a session then use it
            new Doofer().getSessionUtil(params).withSession {      // see comment 1
                // Drilldown from the base source dir
                new File(params.source).eachFileRecurse { sourceFile ->
                    // Construct target path
                    def targetFilePath = "$params.target/$sourceFile".replace('\\', '/')
                    def targetDir = new File(targetFilePath).parent.toString().replace('\\', '/')

                    // import away!
                    if(!sourceFile.toString().contains("\\.svn")) { // ignore subversion-related dirs and folders
                        if(sourceFile.file){                        // ignore dirs as importDocument() creates all necessary folders
                            // see comment 2
                            importDocument(sourcePath: sourceFile.absolutePath, targetPath: targetDir, objectType: objectType)
                            println "imported object -> $targetFilePath"
                        }
                    }
                }
            }
        } else {
            println 'You must specify the target path to import to'
        }
    }

    // entry point to script
    static main(args) {
        if(args?.size() == 4) {
            new Importer(username: args[0], password: args[1], repository: args[2], target: args[3]).execute()
            System.exit(0)
        } else {
            println 'Usage: Importer.groovy username password repository target_path'
            System.exit(1)
        }
    }
}

/*
Comment 1
Calling the withSession() method opens a session then places the following
closure (code block) within the context of the session object. We can now
invoke any of IDfSession methods without specifying the session variable name.
the session is automatically released once the closure code has been executed.

Comment 2
The importDocument() method has been injected into the IDfSession interface
by Doofer so we can execute it - see comment 1 for an explanation of why we
don't need to precede the call with 'session.'.
*/